<?php


class Core_EditorController extends Zend_Controller_Action
{

	public function formAction()
	{

		$request = $this->getRequest();

		$redirect = $request->getParam('redirect', $request->getRequestUri());
		$tablename = $request->getParam('table', '');
		if(empty($tablename)) {
			throw new Exception('Core_FormController::editAction(): Table is empty');
		}

		if(!WSB_Db_Tables::hasDbClass($tablename)) {
			throw new Exception("Core_FormController::editAction(): No DbClass for table '$tablename'");
		}
		$dbClass = WSB_Db_Tables::getDbClass($tablename);


		$table = new $dbClass();

		$primary = $table->getPrimary();
    	$foreignKeys = array();

		$id = intval($request->getParam($primary));
		if($id == 0) {
			$item = $table->createRow();
			if($this->getRequest()->isPost()) {
				$item->setFromArray($request->getParam($table->getClass()));
			}
		} else {
			$where = array($primary . '= ?', $id);
			$collection = $table->find($where);
			$item = $collection->current();
		}

		// Lade Daten von der DB
		$session = $this->getHelper('Session');
        if($session->instance_id > 0) {
            $item->instance_id = $session->instance_id;
        }

		// Falls per GET ein Foreignkey uebergeben wurde,
		// lade diesen Wert ebenfalls
		foreach($foreignKeys AS $fk) {
			$tmpFk = intval($request->getParam($fk));
			if($tmpFk > 0) {
				if(intval($table->$fk) == 0) {
					$table->$fk = $tmpFk;
				}
			}
		}

		$editor = $item->getFormEditor();
		$editor->setFormAction($_SERVER['REQUEST_URI']);
		$editor->addSubmit(WSB_BTN_SAVE, array('label' => 'button:save'));
		$editor->addSubmit(WSB_BTN_SAVE_CLOSE, array('label' => 'button:save/close'));
		$editor->addButton(WSB_BTN_CANCEL, array('label' => 'button:cancel', 'onclick' => sprintf("javascript:window.location.href='%s';", $redirect)));
		$editor->setRedirect($redirect);
		$form = $editor->getForm();

		if($request->isPost() && $form->isValid($request->getPost())) {
			// Gefilterte Werte uebergeben
			$values = $form->getValues();
			unset($values['action']);
			$this->_forward('save', 'db', 'core', $values);
			return;
		} else {
			echo $form->render();
		}

	}

	public function viewAction()
	{

	}

	/**
	 * Die Default LIST Action
	 *
	 */
    public function listAction()
    {

		$request = $this->getRequest();

		$tablename = $request->getParam('table', '');
		if(empty($tablename)) {
			throw new Exception('Core_FormController::listAction(): Table is empty');
		}

		if(!WSB_Db_Tables::hasDbClass($tablename)) {
			throw new Exception("Core_FormController::listAction(): No DbClass for table '$tablename'");
		}
		$this->_models[] = WSB_Db_Tables::getDbClass($tablename);


        //$session = $this->getHelper('Session');
		$session = $this->_getSession();

        // Hole Array $sessionPairs aus Sessionobjekt
		$sessionPairs = $session->models;

		$config = Zend_Registry::get('Zend_Config');
        $modelIndex = $this->_getParam('model', 0);

		// Sessionvariablen Initialisieren
        foreach($this->_models AS $key=>$model) {
            // Filter
            if(!isset($sessionPairs[$key]['filter'])) {
                $sessionPairs[$key]['filter'] = array();
            }
            // Offset
            if(!isset($sessionPairs[$key]['offset'])) {
                $sessionPairs[$key]['offset'] = 0;
            }
            // Order
            if(!isset($sessionPairs[$key]['order'])) {
                $prototype = new $model();
                $sessionPairs[$key]['order'] = $prototype->getOrder();
            }
        }


        // ------------------------------------------------------------------
		// Parameter fuer Filterung.
        $filter = $this->_getParam('filter', array());
        $filterModelIndex = isset($filter['model']) ? $filter['model'] : 0;
        if(key_exists('set', $filter)) {
            $sessionPairs[$filterModelIndex]['filter'] = $filter;
        }
        if(key_exists('reset', $filter)) {
            $sessionPairs[$filterModelIndex]['filter'] = array();
        }
		// ------------------------------------------------------------------


		// ------------------------------------------------------------------
    	// Parameter fuer Paginierung
		$count = $config->application->paginationCount;
		$offset = $this->_getParam('offset');
		if(is_numeric($offset)) {
			if($offset < 0) {
				$offset = 0;
			}
			$sessionPairs[$modelIndex]['offset'] = $offset;
		}
		// ------------------------------------------------------------------

		// ------------------------------------------------------------------
		// Einfaches Ordering
		if($this->_getParam('order') != '') {

			// In $this->_getParam('order') steht nur das Feld
			// In der Session wird aber auch die Sortierrichtung gespeichert, also z.B. "id ASC"
			$oldOrderParts = WSB_Div::csvToArray($sessionPairs[$modelIndex]['order'], ' ');
			$oldOrderField = $sessionPairs[$modelIndex]['order'];
			$oldOrderDirection = 'ASC';
			if(count($oldOrderParts) == 1) {
				$oldOrderField = $oldOrderParts[0];
				$oldOrderDirection = 'ASC';
			}
			if(count($oldOrderParts) >= 2) {
				$oldOrderField = $oldOrderParts[0];
				$oldOrderDirection = $oldOrderParts[1];
			}

			$newOrderField = $this->_getParam('order');
			$newOrderDirection = 'ASC';
			if($newOrderField == $oldOrderField) {
				if($oldOrderDirection == 'ASC') {
					$newOrderDirection = 'DESC';
				} elseif ($oldOrderDirection == 'DESC') {
					$newOrderDirection = 'ASC';
				}
			}

			$sessionPairs[$modelIndex]['order'] = $newOrderField . ' ' . $newOrderDirection;
		}
		// ------------------------------------------------------------------

		// Titel
		$this->view->titleType = 'h1';
		if(count($this->_models) > 1) {
            $this->view->titleType = 'h2';
		}

        foreach($this->_models AS $key=>$model) {

        	$order  = $sessionPairs[$key]['order'];
            $filter = $sessionPairs[$key]['filter'];
            $offset = $sessionPairs[$key]['offset'];
            $prototype = new $model();
            $this->view->modelIndex = $key;
            $this->view->prototype = $prototype;
    		$this->view->filter = $filter;
    		$this->view->order = $order;
    		$parts = explode(' ', $order);
    		$this->view->orderColumn = isset($parts[0]) ? $parts[0] : '';
    		$this->view->orderDirection = isset($parts[1]) ? $parts[1] : '';
    		$this->view->count = $count;
    		$this->view->offset = $offset;
    		$where = $this->_buildWhereStatement($filter);
    		$this->view->total = $this->_getCountAll($prototype, $where);
        	$this->view->collection = $prototype->fetchAll($where, $order, $count, $offset);
        	$this->view->controller = $this;
    		$this->render('list', null, true);
        }

        // Array $sessionPairs in Sessionobjekt speichern
		$session->models = $sessionPairs;

    }

    private function _getSession()
	{
    	$namespace = 'test';
    	return new Zend_Session_Namespace($namespace);
    }

	private function _getCountAll(WSB_Db_Table $table, array $where)
	{
		$info = $table->info();
		$db = $table->getAdapter();
		$select = $db->select();
		$select->from($info[WSB_Db_Table::NAME], array('count' => 'COUNT(*)'));
	    if(count($where) > 0) {
	    	foreach($where AS $key=>$value) {
	    		$select->where($key, $value);
	    	}
	    }
		$stmt = $select->query();
		$result = $stmt->fetchAll();
		if(is_array($result) && isset($result[0]['count'])) {
			return $result[0]['count'];
		}
		return 0;
	}

	private function _buildWhereStatement(array $filter)
	{
		$session = $this->getHelper('Session');
		$where = array();
		$where['deleted = ?'] = 0;
		if(!empty($session->instance_id)) {
			$where['instance_id=?'] = $session->instance_id;
		}
	    if(key_exists('key', $filter) && ($filter['key'] != '')) {
	        if(key_exists('value', $filter) && ($filter['value'] != '')) {
	        	$where[$filter['key'] . ' LIKE ?'] = '%'.$filter['value'].'%';
	        }
	    }
	    return $where;
	}

	protected function _getModelIndex()
	{
        $modelIndex = $this->_getParam('model', 0);
	    if(array_key_exists($modelIndex, $this->_models)) {
            return $modelIndex;
	    } else {
	        throw new Exception(sprintf('Fehler in WSB_Controller_Action::_getModelInstance(): Key %s nicht vorhanden in Array WSB_Controller_Action::$_models.', $modelIndex));
	    }
	}

	protected function _getModelInstance()
	{
	    $modelIndex = $this->_getModelIndex();
        $class = $this->_models[$modelIndex];
        return new $class();
	}

    public function getDefaultListUrl($offset=null, $order=null, $modelIndex=0)
	{
    	$parameters = array();
    	if($modelIndex > 0) {
    		$parameters['model'] = $modelIndex;
    	}
    	if(isset($offset)) {
    		$parameters['offset'] = $offset;
    	}
    	if(!empty($order)) {
    		$parameters['order'] = $order;
    	}
    	$module = ($this->_request->getModuleName() == 'default') ? null : $this->_request->getModuleName();
    	return WSB_Controller_Url::getUrl($this->_request->getControllerName(), 'list', $parameters, $module);
    }

    public function getDefaultAddUrl($modelIndex=0)
	{
    	$parameters = array();
    	if($modelIndex > 0) {
    		$parameters['model'] = $modelIndex;
    	}
    	$module = ($this->_request->getModuleName() == 'default') ? null : $this->_request->getModuleName();
       	return WSB_Controller_Url::getUrl($this->_request->getControllerName(), 'edit', $parameters, $module);
    }

    public function getDefaultViewUrl($id, $modelIndex=0)
	{
    	$parameters = array('id' => $id);
    	if($modelIndex > 0) {
    		$parameters['model'] = $modelIndex;
    	}
    	$module = ($this->_request->getModuleName() == 'default') ? null : $this->_request->getModuleName();
    	return WSB_Controller_Url::getUrl($this->_request->getControllerName(), 'view', $parameters, $module);
    }

    public function getDefaultEditUrl($id, $modelIndex=0)
	{
    	$parameters = array('id' => $id);
    	if($modelIndex > 0) {
    		$parameters['model'] = $modelIndex;
    	}
    	$module = ($this->_request->getModuleName() == 'default') ? null : $this->_request->getModuleName();
    	return WSB_Controller_Url::getUrl($this->_request->getControllerName(), 'edit', $parameters, $module);
    }

    public function getDefaultSaveUrl($modelIndex=0)
	{
    	$parameters = array();
    	if($modelIndex > 0) {
    		$parameters['model'] = $modelIndex;
    	}
    	$module = ($this->_request->getModuleName() == 'default') ? null : $this->_request->getModuleName();
    	return WSB_Controller_Url::getUrl($this->_request->getControllerName(), 'save', $parameters, $module);
    }

    public function getDefaultDeleteUrl($id, $modelIndex=0)
	{
    	$parameters = array('id' => $id);
    	if($modelIndex > 0) {
    		$parameters['model'] = $modelIndex;
    	}
    	$module = ($this->_request->getModuleName() == 'default') ? null : $this->_request->getModuleName();
    	return WSB_Controller_Url::getUrl($this->_request->getControllerName(), 'delete', $parameters, $module);
    }

    public function getDefaultHideUrl($id, $modelIndex=0)
	{
    	$parameters = array('id' => $id);
    	if($modelIndex > 0) {
    		$parameters['model'] = $modelIndex;
    	}
    	$module = ($this->_request->getModuleName() == 'default') ? null : $this->_request->getModuleName();
    	return WSB_Controller_Url::getUrl($this->_request->getControllerName(), 'hide', $parameters, $module);
    }

    public function getDefaultUnhideUrl($id, $modelIndex=0)
	{
    	$parameters = array('id' => $id);
    	if($modelIndex > 0) {
    		$parameters['model'] = $modelIndex;
    	}
    	$module = ($this->_request->getModuleName() == 'default') ? null : $this->_request->getModuleName();
    	return WSB_Controller_Url::getUrl($this->_request->getControllerName(), 'unhide', $parameters, $module);
    }

    public function buildListItemHtmlLinks(WSB_Db_Row $model, $modelIndex=0)
	{
    	$links = array();
    	array_push($links, $this->_buildEditListItemHtmlLink($model, $modelIndex));
    	array_push($links, $this->_buildDeleteListItemHtmlLink($model, $modelIndex));
    	if(isset($model->hidden)) {
    		array_push($links, $this->_buildHiddenListItemHtmlLink($model, $modelIndex));
    	}
    	return $links;
    }

    protected function _buildViewListItemHtmlLink(WSB_Db_Row $model, $modelIndex=0)
	{
    	return WSB_Controller_Url::getHtmlLink(WSB_Icon::view(), $this->getDefaultViewUrl($model->getPrimaryValue(), $modelIndex));
    }

    protected function _buildEditListItemHtmlLink(WSB_Db_Row $model, $modelIndex=0)
	{
		return WSB_Controller_Url::getHtmlLink(WSB_Icon::edit(), $this->getDefaultEditUrl($model->getPrimaryValue(), $modelIndex));
    }

    protected function _buildDeleteListItemHtmlLink(WSB_Db_Row $model, $modelIndex=0)
	{
    	$url = $this->getDefaultDeleteUrl($model->getPrimaryValue(), $modelIndex);
		return WSB_Controller_Url::getHtmlLink(WSB_Icon::delete(), "javascript:wsbYesNoDialog('".$url."', '".$model->getPrimaryValue()."');");
    	//return WSB_Controller_Url::getHtmlLink(WSB_Icon::delete(), $this->getDefaultDeleteUrl($model->getPrimaryValue(), $modelIndex));
    }

    protected function _buildHiddenListItemHtmlLink(WSB_Db_Row $model, $modelIndex=0)
	{
		if(empty($model->hidden)) {
			return WSB_Controller_Url::getHtmlLink(WSB_Icon::visible(), $this->getDefaultHideUrl($model->getPrimaryValue(), $modelIndex));
		} else {
			return WSB_Controller_Url::getHtmlLink(WSB_Icon::hidden(), $this->getDefaultUnhideUrl($model->getPrimaryValue(), $modelIndex));
		}
    }

}
